from django.db import DatabaseError
from rest_framework import status
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, RetrieveAPIView
from rest_framework.response import Response
from rest_framework_mongoengine.generics import GenericAPIView
from drf_haystack.viewsets import HaystackViewSet

from apps.article.utils import ArticleChannelPagination
from apps.users.models import User
from .serializers import GetChannelsSerializer, ArticleListSerializer, ArticleDetailSerializer, \
    PostArticleSerializer, ArticleSearchSerializer
from .models import Channel, Article, Comment
from rest_framework.permissions import IsAuthenticated, AllowAny


class GetChannelsView(ListAPIView):
    '''
        获取首页左侧栏频道列表
    '''
    serializer_class = GetChannelsSerializer
    queryset = Channel.objects.all().order_by('id')
    pagination_class = ArticleChannelPagination


class ArticleListView(ListAPIView):
    '''
        获取某个频道下的文章列表信息
    '''
    serializer_class = ArticleListSerializer

    def get_queryset(self):
        pk = self.kwargs.get('pk')
        if pk == '-1':
            return Article.objects.all()
        else:
            return Article.objects.filter(channel_id=pk).order_by('-createtime')


class ArticleCollectView(GenericAPIView):
    '''
        添加或者取消收藏
    '''
    permission_classes = [IsAuthenticated]

    def put(self, request, pk):
        article = Article.objects.get(id=pk)
        users = article.collected_users.all()
        if request.user in users:
            article.collected_users.remove(request.user)
            return Response({'message': '取消收藏成功', 'success': True}, status=status.HTTP_200_OK)
        else:
            article.collected_users.add(request.user)
            return Response({'message': '收藏成功', 'success': True}, status=status.HTTP_200_OK)


class ArticleDetailView(RetrieveAPIView):
    '''
        根据id获取某篇文章的详细信息
    '''
    queryset = Article.objects.all()
    serializer_class = ArticleDetailSerializer


class PostArticleView(GenericAPIView):
    '''
        发布文章
    '''
    permission_classes = [IsAuthenticated]

    def post(self, request):
        request.data['user_id'] = request.user.id
        serializer = PostArticleSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'articleid': serializer.data.get('id'), 'message': '成功', 'success': True})
        # response = serializer.data
        # response['user'] = {'username': request.user.username}
        # return Response(response)


class ArticleCommentView(GenericAPIView):
    '''
        发表文章评论
    '''
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        try:
            article = Article.objects.get(id=pk)
        except Article.DoesNotExist:
            return Response({'message': '数据不存在', 'success': False})
        content = request.data.get('content')
        parent_id = request.data.get('parent', None)

        comment = Comment.objects.create(article=article, user=request.user, parent_id=parent_id, content=content)
        if comment:
            return Response({'message': '评论成功', 'success': True})
        else:
            return Response({'message': '评论失败', 'success': False})


class ArticleSearchView(HaystackViewSet):
    '''
        文章搜索
    '''
    serializer_class = ArticleSearchSerializer
    index_models = [Article]






